<template>
  <div id="goods-specs">
    <van-cell-group class="specs-cells">
      <van-cell is-link @click="showPopup = true">
        <div slot="title">
          <span>已选</span>
          <span class="spec-vals">{{ selectedSku ? (specList.length ? selectedSpecVals.join('-') : '默认') : '未选规格' }} {{ buyNum }}件</span>
        </div>
      </van-cell>
    </van-cell-group>
    <van-popup v-model="showPopup" position="bottom" style="height:70%">
      <div class="spec-headr">
        <div class="pic-header">
          <img :src="selectedSpecImg.thumbnail || selectedSku.thumbnail || goods.thumbnail">
        </div>
        <i class="iconfont ea-icon-close" @click="showPopup = false"/>
        <div v-if="promotions_price" class="price-header price">{{ promotions_price }}</div>
        <div v-else class="price-header price">￥{{ selectedSku.price | unitPrice }}</div>
        <div class="sn-header">
          <span>商品编号：</span>
          <span>{{ selectedSku.sn }}</span>
        </div>
      </div>
      <div class="spec-body">
        <div class="spec-sel">
          <span class="tit-spec-body">已选</span>
          <span class="prod-spec-info">{{ selectedSku ? selectedSpecVals.join('-') : '未选规格' }}</span>
          <span class="count-spec-body">{{ buyNum }}件</span>
        </div>
        <div class="spec-list">
          <div class="val-spec" v-for="(spec, specIndex) in specList" :key="specIndex">
            <span class="tit-spec-body">{{ spec.spec_name }}</span>
            <p class="p-spec-body">
              <template v-for="spec_val in spec.valueList" >
                <a
                  :key="spec_val.spec_value_id"
                  v-if="canSelected(specIndex, specList, spec_val)"
                  :class="[spec_val.selected && 'selected', spec.spec_type === 1 && 'spec-image']"
                  @click="handleClickSpec(spec, specIndex, spec_val)"
                  class="item-spec-value"
                >{{ spec_val.spec_value }}</a>
              </template>
            </p>
          </div>
        </div>
        <div class="spec-num">
          <span class="tit-spec-body">数量</span>
          <div class="quantity-wrapper">
            <a class="quantity-decrease" :class="[buyNum < 2 && 'limited']" @click="handleBuyNumChanged('-')"><em class="minus">-</em></a>
            <input type="number" v-model="buyNum" class="quantity number" @change="handleBuyNumChanged(parseInt(buyNum))">
            <a class="quantity-increase" @click="handleBuyNumChanged('+')"><em class="plus">+</em></a>
          </div>
        </div>
        <div></div>
      </div>
      <div class="spec-footer">
        <a
          v-if="goods.is_auth === 0 || goods.goods_off === 0"
          class="buy-btn buy-disabled"
        >{{ goods.is_auth === 0 ? '商品审核中' : '商品已下架' }}</a>
        <template v-else>
          <a class="buy-btn add-cart" @click="$emit('add-cart')">加入购物车</a>
          <a class="buy-btn direct-order" @click="$emit('buy-now')">立即购买</a>
        </template>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import * as API_Goods from '@/api/goods'
  import * as API_Promotions from '@/api/promotions'
  import { Foundation } from '@/ui-utils'
  export default {
    name: 'goods-specs',
    props: ['goods', 'show', 'promotions'],
    data() {
      return {
        showPopup: false,
        // 购买数量
        buyNum: 1,
        // skuMap
        skuMap: new Map(),
        // 规格列表
        specList: [],
        // 被选中规格
        selectedSpec: [],
        selectedSpecVals: [],
        // 规格组合列表
        skusCombination: [],
        // 被选中sku
        selectedSku: '',
        // 被选中的规格图片【如果有】
        selectedSpecImg: '',
        // 没有选中sku，初始化为false
        unselectedSku: false,
        promotions_price: false
      }
    },
    mounted() {
      // 如果是拼团的 获取此商品参与拼团的sku规格列表
      Promise.all([
        this.$route.query.sku_id && this.$route.query.pintuan_id && this.$route.query.from_nav === 'assemble' ?
          API_Promotions.getAssembleSkuList(this.goods.goods_id, this.$route.query.pintuan_id):
          API_Goods.getGoodsSkus(this.goods.goods_id)
      ]).then(responses => {
        const response = responses[0]
        const specList = []
        response.forEach((sku, skuIndex) => {
          const { spec_list } = sku
          const spec_value_ids = []
          let _combination = []
          if (spec_list) {
            spec_list.forEach((spec, specIndex) => {
              const _specIndex = specList.findIndex(_spec => _spec['spec_id'] === spec.spec_id)
              const _spec = {
                spec_id: spec.spec_id,
                spec_name: spec.spec_name,
                spec_type: spec.spec_type
              }
              const _value = {
                spec_value: spec.spec_value,
                spec_value_id: spec.spec_value_id,
                spec_value_index: skuIndex,
                spec_value_img: {
                  original: spec.spec_image,
                  thumbnail: spec.thumbnail
                }
              }
              _combination.push({..._value})
              spec_value_ids.push(spec.spec_value_id)
              if(_specIndex === -1){
                specList.push({..._spec, valueList: [{..._value}]})
              }else if(specList[_specIndex]['valueList'].findIndex(_value => _value['spec_value_id'] === spec['spec_value_id']) === -1) {
                specList[_specIndex]['valueList'].push({ ..._value })
              }
            })
            this.skusCombination.push(_combination)
            this.skuMap.set(spec_value_ids.join('-'), sku)
          } else {
            this.skuMap.set('no_spec', sku)
          }
        })
        this.specList = specList
        // 如果有sku信息，初始化已选规格
        if (this.$route.query.sku_id) {
          this.initSpec()
        } else if (this.specList) {
          //默认选中第一个sku
          const _selectedSpecVals = [];
          this.specList.forEach((spec, specIndex)=> {
            if (Array.isArray(spec.valueList)) {
              spec.valueList.forEach((val, specValIndex) => {
                if (specValIndex === 0) {
                  val.selected = true
                  this.selectedSpec[specIndex] = val.spec_value_id
                  _selectedSpecVals.push(val.spec_value)
                }
              })
            }
          })
          this.$set(this, 'selectedSpecVals', _selectedSpecVals)
          this.handleSelectedSku()
        }
        // 如果没有规格，把商品第一个可选sku给已选择sku
        if (!specList.length) {
          this.selectedSku = this.skuMap.get('no_spec')
        }
      })
    },
    methods: {
      /** 初始化规格 */
      initSpec() {
        let { sku_id } = this.$route.query
        let selectedSpecs = ''
        if (sku_id) {
          sku_id = Number(sku_id)
          this.skuMap.forEach((value, key) => {
            if (value.sku_id === sku_id) {
              selectedSpecs = key.split('-')
            }
          })
        }
        const _selectedSpecVals = []
        this.specList.forEach((spec, specIndex)=> {
          if (Array.isArray(spec.valueList)) {
            spec.valueList.forEach((val, specValIndex) => {
              if (selectedSpecs) {
                const spec_value_id = val.spec_value_id
                if (selectedSpecs.indexOf(String(spec_value_id)) !== -1) {
                  val.selected = true
                  this.selectedSpec[specIndex] = val.spec_value_id
                  _selectedSpecVals.push(val.spec_value)
                }
              } else if (specValIndex === 0) {
                val.selected = true
                this.selectedSpec[specIndex] = val.spec_value_id
                _selectedSpecVals.push(val.spec_value)
              }
            })
          }
        })
        this.$set(this, 'selectedSpecVals', _selectedSpecVals)
        this.handleSelectedSku()
      },
      /** 选择规格 */
      handleClickSpec(spec, specIndex, spec_val) {
        if (spec.spec_type === 1 ) {
          this.selectedSpecImg = JSON.parse(JSON.stringify(spec_val.spec_value_img))
        }
        if (spec_val.selected) return
        spec.valueList.map(item => {
          item.selected = item.spec_value_id === spec_val.spec_value_id
          return item
        })
        this.$set(this.specList, specIndex, spec)
        this.selectedSpec[specIndex] = spec_val.spec_value_id
        this.selectedSpecVals[specIndex] = spec_val.spec_value
        this.handleSelectedSku(true)
      },
      /** 是否可选 */
      canSelected(specIndex, specList, spec_val) {
        if (specIndex) {
          const selectedList = specList[--specIndex].valueList.filter(key => key.selected)
          if (selectedList.length) {
            const spec_id = selectedList[0].spec_value_id
            const _ids = []
            this.skusCombination.forEach(key => {
              key.forEach(item => {
                if (item.spec_value_id === spec_id) {
                  _ids.push([...key])
                }
              })
            })
            return _ids.findIndex(key => (key.findIndex(_spec => _spec.spec_value_id === spec_val.spec_value_id) !== -1) === true) !== -1
          }
          return true
        }
        return true
      },
      /** 购买数量增加减少 */
      handleBuyNumChanged(symbol) {
        if (symbol === '+') {
          const { enable_quantity } = this.selectedSku
          if (enable_quantity === 0) {
            this.$message.error('该规格暂时缺货！')
          } else if (this.buyNum >= enable_quantity) {
            this.$message.error('超过最大库存！')
          } else {
            this.buyNum += 1
          }
        } else if(symbol === '-'){
          if (this.buyNum < 2) {
            this.$message.error('不能再少啦！')
          } else {
            this.buyNum -= 1
          }
        }else{
          const { enable_quantity } = this.selectedSku
          if (isNaN(symbol) && typeof(symbol) === 'number' || symbol < 1) {
            this.$message.error('输入格式有误，请输入正整数！')
            return
          }else if (symbol > enable_quantity ){
            this.$message.error('超过最大库存！')
            return
          }else{
            this.buyNum = symbol
          }
        }
      },
      /** 根据已选规格选出对应的sku */
      handleSelectedSku(falg) {
        let sku
        if (this.selectedSpec.length) {
          const spec_vals = []
          this.selectedSpec.forEach(item => spec_vals.push(item))
          sku = this.skuMap.get(spec_vals.join('-'))
        } else {
          sku = this.skuMap.get('no_spec')
        }
        if (sku) {
          this.selectedSku = sku
          this.unselectedSku = false
          this.goodsInfo = { ...this.goodsInfo, ...sku }
          this.buyNum = sku.enable_quantity === 0 ? 0 : 1
          if (falg) {
            if(!this.promotions || !this.promotions.length) return
            const _promotions = this.promotions.filter(key => key.sku_id === this.selectedSku.sku_id)
            if (_promotions) {
              let _prom = _promotions.filter(key => key.promotion_type === 'GROUPBUY' || key.promotion_type === 'SECKILL')
              if (_prom && _prom[0] && _prom[0].promotion_type === 'GROUPBUY') {
                this.promotions_price = `￥${Foundation.formatPrice(_prom[0].groupbuy_goods_vo.price)}`
              } else if (_prom && _prom[0] && _prom[0].promotion_type === 'SECKILL') {
                this.promotions_price = `￥${Foundation.formatPrice(_prom[0].seckill_goods_vo.seckill_price)}`
              } else {
                this.promotions_price = false
              }
            }
          }
        }
      }
    },
    watch: {
      show: function(newVal) {
        if (newVal) this.showPopup = newVal
      },
      showPopup: function(newVal) {
        if (!newVal) this.$emit('close')
      },
      selectedSku: {
        handler: function (newVal) {
          this.$emit('sku-changed', newVal)
          if(this.$route.query.sku_id && this.$route.query.from_nav === 'assemble') return
          if (this.$route.query.sku_id && this.$route.query.sku_id != newVal.sku_id) {
            this.$router.replace({ path: `/goods/${newVal.goods_id}`, query: {sku_id: newVal.sku_id }})
          }
        },
        deep: true
      },
      buyNum: function (newVal) {
        this.$emit('num-changed', newVal)
      },
      promotions: function (newVal) {
        const _promotions = newVal.filter(key => key.sku_id === this.selectedSku.sku_id)
        const _prom = _promotions.filter(key => key.promotion_type === 'SECKILL' || key.promotion_type === 'GROUPBUY' || key.promotion_type === 'EXCHANGE' )
        // 如果是限时抢购或者团购促销活动不显示原价格
        if (_prom && _prom[0]) {
          if (_prom[0].promotion_type === 'SECKILL') {
            this.promotions_price = `￥${Foundation.formatPrice(_prom[0].seckill_goods_vo.seckill_price)}`
          } else if (_prom[0].promotion_type === 'GROUPBUY') {
            this.promotions_price = `￥${Foundation.formatPrice(_prom[0].groupbuy_goods_vo.price)}`
          } else if (_prom[0].promotion_type === 'EXCHANGE') {
            this.promotions_price = `${_prom[0].exchange.exchange_point}积分+￥${Foundation.formatPrice(_prom[0].exchange.exchange_money)}`
          } else {
            this.promotions_price = false
          }
        }
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  @import "../../assets/styles/color";
  /deep/ {
    .van-popup { overflow: visible }
    .spec-vals {
      margin-left: 5px;
      font-size: 12px;
      color: #252525;
    }
  }
  .spec-headr {
    position: relative;
    width: 100%;
    height: 84px;
    &::after {
      position: absolute;
      content: '';
      transform: scaleY(.5);
      bottom: -1px;
      left: 0;
      width: 100%;
      height: 1px;
      border-bottom: 1px solid #e3e5e9;
      z-index: 10;
    }
    .pic-header {
      position: absolute;
      left: 8px;
      top: -26px;
      width: 100px;
      height: 100px;
      border-radius: 3px;
      border: 1px solid #f0f1f3;
      background-color: #fff;
      overflow: hidden;
      display: -webkit-box;
      -webkit-box-pack: center;
      -webkit-box-align: center;
      img {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    }
    .ea-icon-close {
      position: absolute;
      top: 0;
      right: 0;
      width: 44px;
      height: 44px;
      text-align: center;
      line-height: 44px;
    }
    .price-header {
      font-size: 15px;
      line-height: 15px;
      padding-top: 42px;
      padding-left: 121px;
      font-weight: 700;
    }
    .sn-header {
      font-size: 11px;
      line-height: 11px;
      color: #81838e;
      padding-top: 8px;
      padding-left: 121px;
    }
  }
  .spec-body {
    padding: 0 10px;
    height: calc(100% - 84px - 43px);
    overflow-x: hidden;
    overflow-y: scroll;
    .spec-sel {
      padding-top: 15px;
      padding-bottom: 15px;
      .prod-spec-info {
        margin-left: 5px;
        margin-right: 10px;
        font-size: 13px;
        color: #252525;
        line-height: 18px;
      }
      .count-spec-body {
        margin-left: 5px;
      }
    }
    .spec-list {
      .val-spec {
        margin: 13px 0;
        font-size: 0;
        overflow: hidden;
        position: relative;
      }
      .p-spec-body {
        margin-left: 34px;
        overflow: hidden;
      }
      .item-spec-value {
        height: 27px;
        border: 1px solid #bfbfbf;
        border-radius: 4px;
        line-height: 25px;
        font-size: 13px;
        color: #232326;
        float: left;
        margin-right: 10px;
        padding-left: 20px;
        padding-right: 20px;
        margin-bottom: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        min-width: 69px;
        max-width: 98%;
        box-sizing: border-box;
        text-align: center;
        &.selected {
          border: 1px solid $color-main;
          color: $color-main;
        }
      }
    }
    .spec-num {
      .quantity-wrapper {
        display: inline-block;
        height: 26px;
        border-radius: 5px;
        margin-left: 8px;
        float: left;
        line-height: 26px;
        em {
          background: url("") no-repeat;
          background-size: 100px 100px;
          height: 12px;
          width: 12px;
          display: block;
          margin: 6px;
        }
      }
      .quantity-decrease, .quantity-increase {
        background: #fff;
        border: 1px solid #cbcbcb;
        color: #232326;
        display: block;
        height: 24px;
        line-height: 24px;
        width: 26px;
        overflow: hidden;
        text-indent: -200px;
        box-sizing: border-box;
      }
      .quantity {
        color: #232326;
        border: solid #cbcbcb;
        border-width: 1px 0 1px 0;
        height: 24px;
        line-height: 24px;
        width: 34px;
        border-radius: 0;
        -webkit-appearance: none;
        box-sizing: border-box;
      }
      .quantity-decrease, .quantity-increase, .quantity {
        float: left;
        font-size: 15px;
        text-align: center;
      }
      .quantity-decrease {
        em {
          background-position: -32px -85px;
        }
        &.limited em {
          background-position: -45px -85px;
        }
      }
      .quantity-increase {
        em {
          background-position: -32px -67px;
        }
        &.limited em {
          background-position: -45px -67px;
        }
      }
    }
    .tit-spec-body {
      float: left;
      line-height: 18px;
      font-size: 13px;
      color: #81838e;
      width: 26px;
      white-space: normal;
      word-break: break-all;
      height: auto;
    }
  }
  .spec-footer {
    display: flex;
    height: 43px;
    .buy-btn {
      display: block;
      height: 43px;
      width: 1%;
      flex: 1;
      font-size: 15px;
      line-height: 43px;
      color: #fff;
      text-align: center;
    }
    .add-cart {
      background-color: #ffb03f;
    }
    .direct-order {
      background-color: #f23030;
    }
  }
</style>
